package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.OrderLifecycleUtil;

public class PayOrdersTimeoutCleanJob extends GopayBaseJob {
    public static final String TRANSTYPE = "00100";
    private Logger logger = LoggerFactory.getLogger(PayOrdersTimeoutCleanJob.class);
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    private static final int QUERYCOUNT = 5000;

    // private static final int REMAINDER = QUERYCOUNT -1;
    @Resource(name = "cpsGeneralMainOrderOperClient")
    public void setCpsGeneralMainOrderOperClient(MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
        this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
    }

    @Resource(name = "cpsGeneralMainOrderDAO")
    public void setCpsGeneralMainOrderDAO(CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO) {
        this.cpsGeneralMainOrderDAO = cpsGeneralMainOrderDAO;
    }

    @Override
    public void doJobInternal() {
        
        Map param = new HashMap();
        String B2bName = TRANSTYPE + OrderLifecycleUtil.B2B;
        String B2cName = TRANSTYPE + OrderLifecycleUtil.B2C;
        String b2c = OrderLifecycleUtil.getLifecycle(B2cName);
        String b2b = OrderLifecycleUtil.getLifecycle(B2bName);
        param.put("b2b", b2b);
        param.put("b2c", b2c);
        // logger.info("开始查询超时订单");
        // int count =cpsGeneralMainOrderDAO.findTimeoutOrdersInPayCount(param);
        // logger.info("查询超时订单结束count=" + count);
        // logger.info("判断开始count=" + count);
        // if(count==0){
        // logger.info("没有超时的订单count=" + count);
        // return;
        // }
        // logger.info("判断结束count=" + count);
        // 循环次数
        // int i = (count+REMAINDER)/QUERYCOUNT;
        // logger.info("循环次数i=" + i);
        // logger.info("开始循环");
        // for (int j = 0; j < i; j++) {
        // 每次1000条
        long startMillions = System.currentTimeMillis();
        logger.info("查询超时订单执行开始 ");
        List<Object> orderList = cpsGeneralMainOrderDAO.findTimeoutOrdersInPay(param, 1, QUERYCOUNT);
        updateStatus(orderList);
        long endMiilions = System.currentTimeMillis();
        long result = (endMiilions - startMillions) / 1000;
        logger.info("超时订单执行结束 耗费=" + result + "秒");
        // add by fanghw 20150720
        // 让线程睡眠,释放点cpu给EventsHandlerJob使用,否则EventsHandlerJob会假死长达18分钟
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            logger.info("线程睡眠出现异常", e);
//        }
        // }
        // logger.info("结束循环");

        
    }

    private void updateStatus(List<Object> orderList) {
        if (!(orderList.isEmpty())) {
            String txnStaCode = String.valueOf(TxnStaCode.TXN_STA_CD_20002.value);
            logger.info("pay timeout orders Id:" + orderList.toString());
            logger.info("found" + orderList.size() + "other orders  records, overtime timeout order clean-up work now!");

            Map<MainOrderField, String> map = new HashMap<MainOrderField, String>();

            map.put(MainOrderField.TXN_STA_CD, txnStaCode);
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            map.put(MainOrderField.TRAN_FINISH_TIME, sf.format(new Date()));
            for (Object obj : orderList) {

                String gopayOrderId = String.valueOf(obj);
                try {
                    cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, map);

                } catch (GopayException e) {
                    logger.error("update order fail,orderId:" + gopayOrderId.toString(), e);
                } catch (Exception e) {
                    logger.error("update order fail,orderId:" + gopayOrderId, e);
                }

            }

        }
    }
}
